import { http } from "@/utils/http";
import axios from 'axios';
import { useApartmentUserStoreHook } from "@/store/modules/apartmentUser";

// Create an axios instance with default config
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000',
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // Needed for cookies/authentication
});

export type UserProfile = {
  id: string;
  name?: string;
  nickname?: string;
  email: string;
  avatarUrl?: string;
  level?: string;
  expirationDate?: string;
};

export interface UpdateUserProfileDto {
  name?: string;
  nickname?: string;
  email?: string;
  avatarUrl?: string;
}

export type UserResult = {
  success: boolean;
  data: {
    /** 头像 */
    avatar: string;
    /** 用户名 */
    username: string;
    /** 昵称 */
    nickname: string;
    /** 当前登录用户的角色 */
    roles: Array<string>;
    /** 按钮级别权限 */
    permissions: Array<string>;
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

export type RefreshTokenResult = {
  success: boolean;
  data: {
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

/** 登录 */
export const getLogin = (data?: object) => {
  return http.request<UserResult>("post", "/login", { data });
};

/** 刷新`token` */
export const refreshTokenApi = (data?: object) => {
  return http.request<RefreshTokenResult>("post", "/refresh-token", { data });
};

/**
 * Get current user profile from store ID
 */
export const getCurrentUserProfile = async (): Promise<UserProfile> => {
  const apartmentUserStore = useApartmentUserStoreHook();
  const userId = apartmentUserStore.userId;
  return getUserProfile(userId);
};

// Get user profile by ID
export const getUserProfile = async (userId: string): Promise<UserProfile> => {
  try {
    const response = await api.get(`/apartment-user/profile/${userId}`);
    
    // Update store with the user ID from the API response
    if (response.data && response.data.id) {
      const apartmentUserStore = useApartmentUserStoreHook();
      apartmentUserStore.setUserId(response.data.id);
    }
    
    return response.data;
  } catch (error) {
    console.error('Error fetching user profile:', error);
    throw error;
  }
};

// Update user profile
export const updateUserProfile = async (userId: string, data: UpdateUserProfileDto): Promise<UserProfile> => {
  try {
    const response = await api.patch(`/apartment-user/${userId}`, data);
    return response.data;
  } catch (error) {
    console.error('Error updating user profile:', error);
    throw error;
  }
};

// Default export with all user-related API functions
export default {
  getUserProfile,
  updateUserProfile,
  getCurrentUserProfile,
  getLogin,
  refreshTokenApi
};
